
import math

class Vector:
	'Represents a 2D vector.'
	def __init__(self, x = 0.0, y = 0.0):
		self.x = float(x)
		self.y = float(y)
		
	def __add__(self, val):
		return Vector( self.x + val.x, self.y + val.y )

	def __sub__(self,val):
		return Vector( self.x - val.x, self.y - val.y )

	def __iadd__(self, val):
		self.x = val.x + self.x
		self.y = val.y + self.y
		return self
		
	def __isub__(self, val):
		self.x = self.x - val.x
		self.y = self.y - val.y
		return self

	def __div__(self, val):
		return Vector( self.x / val, self.y / val )

	def __mul__(self, val):
		return Vector( self.x * val, self.y * val )

	def __idiv__(self, val):
		self.x = self.x / val
		self.y = self.y / val
		return self
		
	def __imul__(self, val):
		self.x = self.x * val
		self.y = self.y * val
		return self
	
	def __str__(self):
		return "(%.3f, %.3f)" % (self.x, self.y,)
	def __repr__(self):
		return "(%.3f, %.3f)" % (self.x, self.y,)

	def distance_sqrd( self, point2 ):
		'Returns the distance between two points squared. Marginally faster than Distance()'
		return ( (self.x-point2.x)**2 + (self.y-point2.y)**2)
	def distance( self, point2 ):
		'Returns the distance between two points'
		return math.sqrt( self.distance_sqrd(point2) )
	def length_sqrd( self ):
		'Returns the length of a vector sqaured. Faster than Length(), but only marginally'
		return self.x**2 + self.y**2
	def length( self ):
		'Returns the length of a vector'
		return math.sqrt( self.length_sqrd() )
	def normalize( self ):
		'Returns a new vector that has the same direction as vec, but has a length of one.'
		if( self.x == 0. and self.y == 0. ):
			return Vector(0.,0.)
		return self / self.length()
	def dot( self,b ):
		'Computes the dot product of self and b'
		return self.x*b.x + self.y*b.y
	def project_onto( self,v ):
		'Projects self onto v.'
		return v * self.dot(v) / v.length_sqrd()
	
	def copy(self):
		return Vector(self.x, self.y)
	
	def rotate(self, angle):
		angle += math.atan2(self.y, self.x)
		l = self.length()
		self.x = math.cos(angle) * l
		self.y = math.sin(angle) * l
	
	def get_angle(self):
		return math.atan2(self.y, self.x)
	
	def to_int(self):
		return ( int(round(self.x)), int(round(self.y)), )
		
	def export(self):
		from visual import vector as visual_vector
		ret = visual_vector(self.x, self.y, 0)
		return ret

